package org.trajectory.query;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class QuerySerializer {
	private Query query;
	private Document dom;
	public QuerySerializer(Query query){
		this.query = query;
	}
	public String createXML() throws IOException{
		if(this.query == null)
			throw new NullArgumentException("The query should not be null");
		createDocument();
		createDom();
		XMLOutputter serializer = new XMLOutputter();
		Format format = Format.getPrettyFormat();
		StringWriter st = new StringWriter();
		serializer.setFormat(format);
		serializer.output(this.dom, st);	
		return st.getBuffer().toString();
	}
	
	private void createDocument() {
		this.dom = new Document();
	}
	private void createDom() {
		Element root = new Element("Query");
		addDatasource(root);
		addShop(root);
		addFrom(root);
		addTo(root);
		addLine(root);
		dom.setRootElement(root);
	}
	private void addLine(Element root) {	
		addElement(root, "Line", StringUtils.join(query.getLine(),","));
	}
	private void addTo(Element root) {
		addElement(root, "To", query.getTo().toString());
	}
	private void addFrom(Element root) {
		addElement(root, "From", query.getFrom().toString());
	}
	private void addShop(Element root){
		addElement(root, "Shop", query.getShop());
	}
	private void addDatasource(Element root){
		addElement(root, "Datasource", this.query.getDatasource());
	}
	private void addElement(Element root , String name , String value){
		Element  el = new Element(name);
		el.addContent(value);
		root.addContent(el);
	}
}
